#!/usr/sh
# gitee token: glpat-x9mjtNzphTvsE8TkB6Df
# raw file api: http://sunshinegitlab.sinosig.com/api/v4/projects/1502/repository/files/cvedb.regular/raw?ref=main

latestSha=$(curl --head  -sH "PRIVATE-TOKEN: glpat-x9mjtNzphTvsE8TkB6Df"  http://sunshinegitlab.sinosig.com/api/v4/projects/1502/repository/files/cvedb.regular/raw?ref=main | sed -En 's;X-Gitlab-Content-Sha256:\s+([^ ]+)\r;\1;p')
if [[ "$latestSha" == "" ]];then
    echo "fetch checksum from sunshinegitlab failed, please retry !";
    exit 1;
fi

echo "the latest file sha256: $latestSha"
if [[ ! -f "/etc/neuvector/db/cvedb" ]];then
    echo ">>> Initing New file <<<";
    curl -H "PRIVATE-TOKEN: glpat-x9mjtNzphTvsE8TkB6Df"  http://sunshinegitlab.sinosig.com/api/v4/projects/1502/repository/files/cvedb.regular/raw?ref=main > /etc/neuvector/db/cvedb;
fi

if [[ "$?" -ne 0 ]];then
    echo "download file from sunshinegitlab failed, please retry !";
    exit 1;
fi

currentSha=$(sha256sum /etc/neuvector/db/cvedb| egrep -o "^[^ ]+")
echo "   current file sha256: $currentSha"

if [[ $latestSha != $currentSha ]];then
    echo ">>> updating files <<<";
    mv /etc/neuvector/db/cvedb /etc/neuvector/db/cvedb.old
    curl -H "PRIVATE-TOKEN: glpat-x9mjtNzphTvsE8TkB6Df"  http://sunshinegitlab.sinosig.com/api/v4/projects/1502/repository/files/cvedb.regular/raw?ref=main > /etc/neuvector/db/cvedb;
else
    echo "current file is already updated"
    exit 0;
fi

if [[ "$?" -ne 0 ]];then
    echo "updating file from sunshinegitlab failed, please retry !";
    exit 1;
fi
updateSha=$(sha256sum /etc/neuvector/db/cvedb| egrep -o "^[^ ]+")
echo "       updated sha256: $updateSha"
if [[ $latestSha == $updateSha ]];then
    echo "updated file checksum failed, please check !";
    mv /etc/neuvector/db/cvedb.old /etc/neuvector/db/cvedb
    echo "old file recovered";
    exit 1;
fi
exit 127;